<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/3/31 14:19
 */

namespace App\Utils;


use GeoIp2\Database\Reader;
use Exception;
class IpAddressUtils
{

    private $language = 'zh-CN';

    private $record;

    public function __construct(string $ip)
    {
        try {
            $cityDbReader = new Reader(BASE_PATH . '/storage/geoIp2/GeoLite2-City.mmdb');

            $this->record = $cityDbReader->city($ip);
        }catch (Exception $e)
        {
            $this->record = null;
        }

    }

    /**
     * 国家名称
     * @return mixed
     */
    public function getCountryName()
    {
        try {
            return $this->record->country->names[$this->language];
        }catch (Exception $e)
        {
            return "unknown";
        }

    }


    /**
     * 城市名称
     * @return mixed
     */
    public function getCityName()
    {
        if($this->record)
        {
            return $this->record->city->names[$this->language];
        }
        return "unknown";
    }

    /**
     * 省份名称
     * @return mixed
     */
    public function getProvinceName()
    {
        if($this->record)
        {
            return $this->record->mostSpecificSubdivision->names[$this->language];
        }
        return "unknown";

    }


    /**
     * 国家编码
     * @return string|null
     */
    public function getCountryCode()
    {
        return $this->record->country->isoCode;
    }

    /**
     * 邮编
     * @return string|null
     */
    public function getPostalCode()
    {
        return $this->record->postal->code;
    }


    /**
     * 获取省份和城市
     * @param $split
     * @return string
     */
    public function getProvinceAndCity($split = "-")
    {
        return $this->getProvinceName().$split.$this->getCityName();
    }


    /**
     * 纬度
     * @return float|null
     */
    public function getLocationLatitude()
    {
        return $this->record->location->latitude;
    }

    /**
     * 精度
     * @return float|null
     */
    public function getLocationLongitude()
    {
        return $this->record->location->longitude;
    }
}